package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapBookMark;
import com.guodi.map.service.IMapBookMarkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.*;

/**
 * @描述：书签表 控制类
 * @作者: 陈宏成
 * @日期: 2021-03-30
 */
@RestController
@RequestMapping("MapBookMark")
@Api(value = "API - MapBookMarkController", tags = "地图书签表")
public class MapBookMarkController extends BaseController {

    @Resource
    private IMapBookMarkService iMapBookMarkService;

    /**
     * @描述：新增地图书签记录
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "书签名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "extent", value = "范围", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "layer", value = "图层", required = true, dataType = "string", paramType = "query"),
    })
    @Transactional(rollbackFor = Exception.class)
    public R<MapBookMark> save(@ApiIgnore MapBookMark mapBookMark){
        // 新增前的验证数据，填充数据
        R<MapBookMark> prepareBeforeSaveResult = this.prepareBeforeSave(mapBookMark);
        if (prepareBeforeSaveResult != null){
            return prepareBeforeSaveResult;
        }
        boolean save = this.iMapBookMarkService.save(mapBookMark);
        if (save){
            return R.data(mapBookMark);
        }else{
            return R.fail(StatusCode.ERROR_CODE_40005,"新增失败");
        }
    }

    /**
     * @描述：修改地图书签记录
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "书签名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "extent", value = "范围", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "layer", value = "图层", required = true, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R<MapBookMark> update(@ApiIgnore MapBookMark mapBookMark){
        // 修改前的验证数据，填充数据
        R<MapBookMark> prepareBeforeUpdateResult = this.prepareBeforeUpdate(mapBookMark);
        if (prepareBeforeUpdateResult != null){
            return prepareBeforeUpdateResult;
        }
        boolean update = this.iMapBookMarkService.updateById(mapBookMark);
        if (update){
            return R.data(mapBookMark);
        }else{
            return R.fail(StatusCode.ERROR_CODE_40005,"修改失败");
        }
    }

    /**
     * @描述：删除地图书签记录
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "主键id，如果多个，英文逗号隔开", required = true, dataType = "string", paramType = "query")
    })
    public R delete(String ids){
        if (!StringUtils.hasText(ids)){
            return R.fail(StatusCode.ERROR_CODE_40005,"主键ID不能为空");
        }
        List<String> idList = Arrays.asList(ids.trim().split(","));
                    List<MapBookMark> mapBookMarks = this.iMapBookMarkService.deleteByIds(idList, this.getUser().getUserId().toString());
                    return R.data(mapBookMarks);
                    }

                    /**
                     * @描述：获取地图书签记录列表
                     * @作者: 陈宏成
                     * @日期: 2021-03-30
                    */
                    @PostMapping("/list")
                    @ApiOperation(value = "获取列表")
                    @ApiImplicitParams({
                    @ApiImplicitParam(name = "size", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码",  dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "书签名称",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isPage", value = "是否分页，默认分页，如果为false，则不分页",  dataType = "boolean", paramType = "query")
    })
    public R<Map<String, Object>> list(@ApiIgnore Page page, String name, Boolean isPage){
        LambdaQueryWrapper<MapBookMark> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(StringUtils.hasText(name),MapBookMark::getName,StringUtils.hasText(name)?name.trim():name);
        lambdaQueryWrapper.eq(MapBookMark::getCreator,this.getUser().getUserId().toString());
        lambdaQueryWrapper.orderByDesc(MapBookMark::getCreateTime);
        Map<String, Object> result = new HashMap<>();
        if (isPage == null || isPage){
            Page page1 = this.iMapBookMarkService.page(page, lambdaQueryWrapper);
            result.put("size",page.getSize());
            result.put("current",page.getCurrent());
            result.put("total",page1.getTotal());
            result.put("records",page1.getRecords());
        }else {
            List<MapBookMark> list = this.iMapBookMarkService.list(lambdaQueryWrapper);
            result.put("total",list.size());
            result.put("records",list);
        }
        return R.data(result);
    }

    /**
     * @描述：获取地图书签记录详情
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    @PostMapping("/detail")
    @ApiOperation(value = "获取详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query")
    })
    public R<MapBookMark> detail(String id){
        if (!StringUtils.hasText(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"主键id不能为空");
        }
        LambdaQueryWrapper<MapBookMark> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(MapBookMark::getCreator,this.getUser().getUserId().toString());
        lambdaQueryWrapper.eq(MapBookMark::getId,id);
        MapBookMark bookMark = this.iMapBookMarkService.getOne(lambdaQueryWrapper, false);
        if (bookMark == null){
            return R.fail(StatusCode.ERROR_CODE_40005,"记录不存在");
        }
        return R.data(bookMark);
    }

    /**
     * @描述：修改前的准备，包括验证数据和填充数据
     * @入参：mapBookMark
     * @出参：如果返回null，则表示无任何问题，如果有返回，则说明有问题需要返回给前端
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    private R<MapBookMark> prepareBeforeUpdate(MapBookMark mapBookMark){
        // 验证非空数据项
        if (!StringUtils.hasText(mapBookMark.getId())){
            return R.fail(StatusCode.ERROR_CODE_40005,"主键id不能为空");
        }
        if (!StringUtils.hasText(mapBookMark.getName())){
            return R.fail(StatusCode.ERROR_CODE_40005,"书签名不能为空");
        }
        if (!StringUtils.hasText(mapBookMark.getExtent())){
            return R.fail(StatusCode.ERROR_CODE_40005,"范围不能为空");
        }
        // 验证重名数据项
        MapBookMark bookMarkByName = this.iMapBookMarkService.getByEqName(mapBookMark.getName(), this.getUser().getUserId().toString());
        if (bookMarkByName != null && !mapBookMark.getId().equalsIgnoreCase(bookMarkByName.getId())){
            return R.fail(StatusCode.ERROR_CODE_40005,"该书签名已存在");
        }
        // 判断是否是自己的记录
        MapBookMark bookMark = this.iMapBookMarkService.getById(mapBookMark.getId());
        if (bookMark == null){
            return R.fail(StatusCode.ERROR_CODE_40005,"记录不存在");
        }
        if (!this.getUser().getUserId().toString().equals(bookMark.getCreator())){
            return R.fail(StatusCode.ERROR_CODE_40005,"不能修改他人记录");
        }
        mapBookMark.setCreator(bookMark.getCreator());
        mapBookMark.setCreateTime(bookMark.getCreateTime());
        mapBookMark.setModifier(this.getUser().getUserId().toString());
        mapBookMark.setModifyTime(new Date());
        return null;
    }

    /**
     * @描述：新增前的准备，包括验证数据和填充数据
     * @入参：mapBookMark
     * @出参：如果返回null，则表示无任何问题，如果有返回，则说明有问题需要返回给前端
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    private R<MapBookMark> prepareBeforeSave(MapBookMark mapBookMark){
        // 验证非空数据项
        if (!StringUtils.hasText(mapBookMark.getName())){
            return R.fail(StatusCode.ERROR_CODE_40005,"书签名不能为空");
        }
        // 验证重名数据项
        MapBookMark bookMarkByName = this.iMapBookMarkService.getByEqName(mapBookMark.getName(), this.getUser().getUserId().toString());
        if (bookMarkByName != null){
            return R.fail(StatusCode.ERROR_CODE_40005,"该书签名已存在");
        }
        if (!StringUtils.hasText(mapBookMark.getId())){
            mapBookMark.setId(UuidUtil.get32UUID());
        }
        mapBookMark.setCreator(this.getUser().getUserId().toString());
        mapBookMark.setCreateTime(new Date());
        mapBookMark.setModifier(null);
        mapBookMark.setModifyTime(null);
        return null;
    }
}
